//
//  WangCardViewController.swift
//  WangPu
//
//  Created by xiaozhi on 15/10/24.
//  Copyright © 2015年 zhixiao. All rights reserved.
//

import UIKit

class WangCardViewController: BaseViewController {
    var pwdField:UITextField!
    var field1:UITextField!
    var field2:UITextField!
    var field3:UITextField!
    var field4:UITextField!
    var field5:UITextField!
    var feedBtn:UIButton!
    var qureyBtn:UIButton!
    var changeNumber:NSInteger = 3
    var restMoney:UILabel!
    var line:UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "旺卡"
        let backItem = UIBarButtonItem(image: UIImage(named: "back_icon"), style:UIBarButtonItemStyle.Plain, target:self, action:"goBack")
        backItem.tintColor = UIColor.whiteColor()
        self.navigationItem.leftBarButtonItem = backItem
        self.automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = commonBackgoundColor
        
        let baseHieght:CGFloat = 40.0
        let labelX:CGFloat = 32.0
        let offsetX:CGFloat = 10.0
        let line1 = UIView(frame: CGRectMake(0, 74, view.bounds.size.width, baseHieght*2+10))
        line1.backgroundColor = UIColor.whiteColor()
        let userImgView = UIImageView(frame: CGRectMake(offsetX, 12, 16, 16))
        userImgView.image = UIImage(named: "password")
        line1.addSubview(userImgView)
        let note1 = UILabel(frame: CGRectMake(labelX, 0, 75, baseHieght))
        note1.text = "旺卡密码"
        note1.font = UIFont.systemFontOfSize(14)
        line1.addSubview(note1)
        pwdField = UITextField(frame: CGRectMake(offsetX, CGRectGetMaxY(note1.frame), line1.bounds.size.width - offsetX*2, baseHieght))
        pwdField.borderStyle = UITextBorderStyle.RoundedRect
        pwdField.font = UIFont.systemFontOfSize(14)
//        pwdField.userInteractionEnabled = false
        
        line1.addSubview(pwdField)
        view.addSubview(line1)
        
//        let lineWidth:CGFloat = 20
//        let field_width:CGFloat = (pwdField.bounds.size.width-lineWidth*4.0)/5.0
//        let field_height = pwdField.bounds.size.height
//        let offsetY:CGFloat = 114
//        field1 = UITextField(frame: CGRectMake(offsetX, offsetY, field_width,field_height))
//        field1.borderStyle = UITextBorderStyle.None
//        field1.font = UIFont.systemFontOfSize(14)
//        field1.delegate = self
//        field1.textAlignment = NSTextAlignment.Center
//        view.addSubview(field1)
//        
//        field2 = UITextField(frame: CGRectMake(offsetX+field_width+lineWidth, offsetY, field_width,field_height))
//        field2.borderStyle = UITextBorderStyle.None
//        field2.font = UIFont.systemFontOfSize(14)
//        field2.delegate = self
//        view.addSubview(field2)
//        
//        field3 = UITextField(frame: CGRectMake(offsetX+(field_width+lineWidth)*2,offsetY, field_width,field_height))
//        field3.borderStyle = UITextBorderStyle.None
//        field3.font = UIFont.systemFontOfSize(14)
//        field3.delegate = self
//        view.addSubview(field3)
//        
//        field4 = UITextField(frame: CGRectMake(offsetX+(field_width+lineWidth)*3,offsetY, field_width,field_height))
//        field4.borderStyle = UITextBorderStyle.None
//        field4.font = UIFont.systemFontOfSize(14)
//        field4.delegate = self
//        view.addSubview(field4)
//        
//        field5 = UITextField(frame: CGRectMake(offsetX+(field_width+lineWidth)*4,offsetY, field_width,field_height))
//        field5.borderStyle = UITextBorderStyle.None
//        field5.font = UIFont.systemFontOfSize(14)
//        field5.delegate = self
//        view.addSubview(field5)
        

        
        let width = (view.bounds.size.width-40)/2.0
        
        feedBtn = UIButton(frame: CGRectMake(10,CGRectGetMaxY(line1.frame)+20, width, 36))
        feedBtn.setTitle("充值到旺卡", forState: UIControlState.Normal)
        feedBtn.backgroundColor = UIColor.whiteColor()
        feedBtn.setTitleColor(commonRedColor, forState: UIControlState.Normal)
        feedBtn.addTarget(self, action: "feedButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        feedBtn.layer.cornerRadius = 4.0
        feedBtn.titleLabel?.font = UIFont.systemFontOfSize(15)
        view.addSubview(feedBtn)
        
        qureyBtn = UIButton(frame: CGRectMake(CGRectGetMaxX(feedBtn.frame)+20,CGRectGetMaxY(line1.frame)+20, width, 36))
        qureyBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        qureyBtn.setTitle("余额查询", forState: UIControlState.Normal)
        qureyBtn.backgroundColor = commonRedColor
        qureyBtn.addTarget(self, action: "quetryButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        qureyBtn.layer.cornerRadius = 4.0
        qureyBtn.titleLabel?.font = UIFont.systemFontOfSize(15)
        view.addSubview(qureyBtn)
        // Do any additional setup after loading the view.
        
        line = UIView(frame: CGRectMake(0, CGRectGetMaxY(qureyBtn.frame)+20, view.bounds.size.width, baseHieght))
        line.backgroundColor = UIColor.whiteColor()
        let userImgView1 = UIImageView(frame: CGRectMake(offsetX, (line.bounds.size.height-16)/2.0, 16, 16))
        userImgView1.image = UIImage(named: "pay_icon")
        line.addSubview(userImgView1)
        let note11 = UILabel(frame: CGRectMake(labelX, 0, 75, baseHieght))
        note11.text = "可用余额"
        note11.font = UIFont.systemFontOfSize(13)
        line.addSubview(note11)
        
        restMoney = UILabel(frame: CGRectMake(view.bounds.size.width-110, 0, 100, baseHieght))
//        point.text = moeny!+"元"
        restMoney.textColor = commonRedColor
        restMoney.textAlignment = NSTextAlignment.Right
        restMoney.font = UIFont.systemFontOfSize(13)
        line.addSubview(restMoney)
        view.addSubview(line)
        line.hidden = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBarHidden = false
    }
    func feedButtonClick()->Void{
        if let name = self.pwdField.text{
            let nameinfo = name.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) as NSString
            if nameinfo.length == 0{
                self.showTips("密码不能为空")
                return
            }
        }
        else{
            self.showTips("密码不能为空")
            return
        }
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject(GlobalDataHelper.instance.session!, forKey: "sessionid")
        parameters.setObject(self.pwdField.text!, forKey: "giftcard")

        
        request.requestStart("/user/redeemGift", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                    dispatch_async(dispatch_get_main_queue()){
                        self.showTips("数据加载出错")
                    }
                    return
                }
                if (dic?["result"])! as! String == "0"{
                    dispatch_async(dispatch_get_main_queue()){
                         self.showTips("充值成功")
                    }
                }
                dispatch_async(dispatch_get_main_queue()){
                    self.showTips(dic?["msg"] as? String)
                }
            }
            else{
                self.showTips("操作失败")
            }
        })
        self.showProcess("操作中...")
    }
    func quetryButtonClick()->Void{
        if let name = self.pwdField.text{
            let nameinfo = name.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) as NSString
            if nameinfo.length == 0{
                self.showTips("用户名不能为空")
                return
            }
        }
        else{
            self.showTips("用户名不能为空")
            return
        }
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject(GlobalDataHelper.instance.session!, forKey: "sessionid")
        parameters.setObject(self.pwdField.text!, forKey: "giftcard")
        
        
        request.requestStart("/user/giftCart", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                    dispatch_async(dispatch_get_main_queue()){
                        self.showTips("数据加载出错")
                    }
                    return
                }
                if (dic?["result"])! as! String == "0"{
                    dispatch_async(dispatch_get_main_queue()){
                        self.line.hidden = false
                        self.restMoney.text = dic?["data"]?["balance"] as? String

                    }
                }
                dispatch_async(dispatch_get_main_queue()){
                    self.showTips(dic?["msg"] as? String)
                }
            }
            else{
                self.showTips("查询失败")
            }
        })
        self.showProcess("查询中...")
    }
    func  goBack(){
        self.navigationController?.popViewControllerAnimated(true)
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
extension WangCardViewController:UITextFieldDelegate{
    func textFieldDidBeginEditing(textField: UITextField){
    }
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool{
//        if let str = textField.text{
//           let currentStr = str as NSString
//            if currentStr.length > changeNumber{
//                return false
//            }
//            if currentStr.length >= changeNumber{
//                switch textField{
//                case field1:
//                   field2.becomeFirstResponder()
//                case field2:
//                    field3.becomeFirstResponder()
//                case field3:
//                    field4.becomeFirstResponder()
//                case field4:
//                    field5.becomeFirstResponder()
//                default:break
//                }
//            }
//        }
        return true
    }
}
